package com.sfac.javaEE.service.Impl;

import com.sfac.javaEE.common.Result;
import com.sfac.javaEE.dao.UserDao;
import com.sfac.javaEE.entity.User;
import com.sfac.javaEE.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class UserServiceImpl implements UserService {

    private UserDao userDao = new UserDao();

    @Override
    public Result<User> insertUser(User user) {
        // 判断用户名是否重复
        User temp = userDao.getUserByUserName(user.getUserName());
        if (temp != null) {
            return new Result<>(
                    Result.ResultStatus.FAILED.code,
                    "User name is repeat.");
        }

        // 设置创建时间
        user.setCreateDate(new Date());

        // 插入 user
        userDao.insertUser(user);
        return new Result<>(
                Result.ResultStatus.SUCCESS.code,
                "Insert success.",
                user);
    }

    @Override
    public Result<User> updatetUser(User user) {
        // 判断用户名是否重复
        User temp = userDao.getUserByUserName(user.getUserName());
        if (temp != null && temp.getId() != user.getId()) {
            return new Result<>(
                    Result.ResultStatus.FAILED.code,
                    "User name is repeat.");
        }

        // 更改 user
        userDao.updateUser(user);
        return new Result<>(
                Result.ResultStatus.SUCCESS.code,
                "Update success.",
                user);
    }

    @Override
    public User getUserById(int id) {
        return userDao.getUserById(id);
    }

    @Override
    public Result<Object> deleteUserById(int id) {
        userDao.deleteUserById(id);
        return new Result<>(
                Result.ResultStatus.SUCCESS.code,
                "Delete success.");
    }

    @Override
    public Result<User> getUserByUserNameAndPassword(HttpServletRequest req,
                                                     String userName, String password) {
        User user = userDao.getUserByUserNameAndPassword(userName, password);
        if (user == null) {
            return new Result<>(
                    Result.ResultStatus.FAILED.code,
                    "User name or password error.");
        } else {
            // 将登陆的用户信息添加到 Session 中
            req.getSession().setAttribute("user", user);
            return new Result<>(
                    Result.ResultStatus.SUCCESS.code,
                    "Login success.",
                    user);
        }
    }

    @Override
    public void loginout(HttpServletRequest req) {
        req.getSession().removeAttribute("user");
    }
}


